/* eslint-disable no-unsafe-optional-chaining */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { DeleteOutlined, ExclamationCircleFilled, ExportOutlined, PlusOutlined } from "@ant-design/icons";

import CustomerTable from "@/components/CustomerTable";
import { SyncOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns } from "@ant-design/pro-components";
import type { FormInstance, MenuProps } from "antd";
import { Button, Divider, Dropdown, Input, Modal, Popconfirm, Space, Typography, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import DictTypeForm, { DictTypeParams } from "./components/dictTypeForm";
import { getDict } from "@/services/api/module/system/dict";
import { getPageList, remove, save, update } from "@/services/api/module/tenant/developer/dictType";
import { syncDict } from "@/services/api/module/tenant/developer/dict";
import FilterDrawer from "@/components/FilterDrawer";
import { dictTabs, createTableColumns, pagination } from "./constants";
import { useRequest } from "ahooks";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
import DictDataTableList from "./components/dictDataTableList";
import { useTableScroll } from "@/hooks/useTableScroll";
const { confirm } = Modal;
const DictTableList: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [open, setOpen] = useState<boolean>(false);
	const [dictTypeOpen, setDictTypeOpen] = useState<boolean>(false);
	const [currentDictType, setCurrentDictType] = useState<string>("");
	const [currentId, setCurrentId] = useState<undefined | number>(undefined);
	const [currentRowId, setCurrentRowId] = useState<undefined | number>(undefined);
	const [modalVisible, setModalVisible] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentRow, setCurrentRow] = useState<any>();
	const [activeKey, setActiveKey] = useState<string>("system");
	const [selectedRows, setSelectedRows] = useState<any>([]);
	const [dictCategory, setDictCapteGory] = useState<any>();
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	const [statusOptions, setStatusOptions] = useState<any>();

	// 初始化字典
	useEffect(() => {
		getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
		getDict("sys_category_type").then(data => {
			setDictCapteGory(data);
		});
	}, []);
	// 列定义
	const handleColumnEditor = (record: any) => {
		setDictTypeOpen(true);
		setCurrentRowId(record.id);
	};
	const handleColumnDetailData = (record: any) => {
		handleOpenData(record.dictName);
		setCurrentDictType(record.dictType);
	};
	const handleColumnRemove = (record: any) => {
		handleRemove(record?.id);
	};
	const columns = createTableColumns(handleColumnEditor, handleColumnDetailData, handleColumnRemove);
	const handleOpenData = (title?: string) => {
		setOpen(!open);
	};
	// 删除
	const handleRemove = async (ids: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: Array<number>, names: Array<string>) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确认删除名称为：${names} 的字典类型？`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};
	// 保存
	const handleSave = async (values: DictTypeParams) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as DictTypeParams)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 修改
	const handleUpdate = async (values: DictTypeParams) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as DictTypeParams)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setDictTypeOpen(false);
		setCurrentRowId(undefined);
		actionRef?.current?.reload();
	};
	// 关闭弹出表单
	const handleCloseForm = async () => {
		setCurrentRowId(undefined);
		setDictTypeOpen(false);
	};
	// 刷新缓存
	const syncCatchDict = async (): Promise<any> => {
		run();
	};
	// 刷新缓存
	const handleAsync = () => {
		return new Promise((reslove, reject) => {
			syncDict()
				.then(res => {
					message.success(res.msg);
					reslove(res);
				})
				.catch(() => {
					reject("");
				});
		});
	};
	// 刷新缓存
	const { loading, run } = useRequest(handleAsync, {
		throttleWait: 3000,
		manual: true
	});
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({
			...params,
			...searchFormValue,
			...searchValue,
			...{
				category: activeKey === "system" ? "0" : "1"
			}
		}).then((data: any) => {
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			userName: value
		});
		actionRef.current?.reload();
	};
	const tableSrcollHeight = useTableScroll({ extraHeight: 300 });

	return (
		<>
			<PanelGroup direction="horizontal">
				<Panel defaultSize={40} minSize={30}>
					<CustomerTable<API.System.DictType>
						actionRef={actionRef}
						formRef={formTableRef}
						rowKey="id"
						key="dictTypeList"
						scroll={{ y: tableSrcollHeight, x: 600 }}
						pagination={pagination}
						toolbar={{
							search: (
								<Space>
									<Input.Search placeholder="配置键" allowClear style={{ width: 200 }} onSearch={handleOnSearch} />
									<FilterDrawer
										columns={columns}
										tableActionRef={actionRef}
										onReset={() => {
											setSearchFormValue(undefined);
											actionRef?.current?.reload();
										}}
										onSubmit={(values: any) => {
											setSearchFormValue(values);
											actionRef?.current?.reload();
										}}
									/>
								</Space>
							)
						}}
						search={false}
						tableAlertRender={false}
						// @ts-ignore
						toolBarRender={() => {
							return (
								<>
									<Button
										type="primary"
										shape="circle"
										key="addDict"
										onClick={() => {
											setDictTypeOpen(true);
										}}
									>
										<PlusOutlined />
									</Button>
									<Button key="syncDict" onClick={syncCatchDict} disabled={loading} shape="circle">
										<SyncOutlined spin={loading} />
									</Button>
									{selectedRows?.length > 0 && (
										<Button
											shape="circle"
											type="primary"
											danger
											key="remove"
											onClick={async () => {
												showRemoveConfirm(
													Array.from(selectedRows, ({ id }) => id),
													Array.from(selectedRows, ({ name }) => name)
												);
											}}
										>
											<DeleteOutlined />
										</Button>
									)}
								</>
							);
						}}
						onRow={record => {
							return {
								onClick: e => {
									// console.log()
									setCurrentDictType(record?.dictType);
									setSelectedRows([record?.id]);
								}
							};
						}}
						// @ts-ignore
						request={tableDataRequest}
						columns={columns}
						rowSelection={{
							selectedRowKeys: selectedRows,
							columnWidth: 20,
							type: "radio",
							onChange: (selectedRowKeys, selectedRows) => {
								setSelectedRows(selectedRowKeys);
							}
						}}
					/>
				</Panel>
				<PanelResizeHandle style={{ width: 5 }} />
				<Panel minSize={50}>
					<DictDataTableList dictType={currentDictType} statusOptions={statusOptions} />
				</Panel>
			</PanelGroup>
			<DictTypeForm
				open={dictTypeOpen}
				onCancel={handleCloseForm}
				dictCategory={dictCategory}
				onSubmit={async (values: DictTypeParams) => {
					return values.id ? await handleUpdate(values) : await handleSave(values);
				}}
				id={currentRowId}
			/>
		</>
	);
};

export default DictTableList;
